package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        //1.调用微信接口,获取openid
        String opnenId = getOpenId(userLoginDTO.getCode());
        log.info("[微信登录,获取openid] openid:{}", opnenId);
        //存数据库
        User user = userMapper.selectByOpenId(opnenId);
        if (user == null) {
            user = new User();
            user.setOpenid(opnenId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //3.生成token
        Map<String, Object> payLoad = new HashMap<>();
        //把数据库用户的ID,存入载荷中
        payLoad.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(), payLoad);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(opnenId);
        userLoginVO.setToken(token);

        return userLoginVO;
    }

    @Resource
    private WeChatProperties weChatProperties;

    private String getOpenId(String code) {
        //直接使用封装的工具类连接微信
        //String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxe22324ee28995b66&secret=efbd61872b8ffdf3a30a520cec4a8765&js_code=0d3GmS0w3AUmu13qfg0w3aJZUs1GmS0a&grant_type=authorization_code";

        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");

        String jsonData = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        //{"":"","":"},丛json中获取openId
        JSONObject jsonObject = JSON.parseObject(jsonData);
        return jsonObject.get("openid").toString();
    }
}
